<?php 
    $exchange = $this->getExchange();
    $imgurl = $this->getSkinUrl('/images/ajax-loader-tr.gif');
 ?>
 <?php if($exchange &&  $exchange->getTemplateId()):
    $href = Mage::helper('core/url')->getHomeUrl()."promotion/exchange/view/exchange_id/".$exchange->getId();
 ?>
    <div><?php echo " 积分兑换地址： " . $href; ?></div>
<?php endif; ?>
<div id="centerimage"><img src="<?php echo $imgurl ?>"/></div>
<div class="content-header">
    <table cellspacing="0">
        <tbody><tr>
            <td style="width:50%;"><h3 class="icon-head head-products">积分兑换管理</h3></td>
            <td class="a-right">

                    <span id="coupons_generate_button"><button id="id_3cf81872242ced1ce5317b5704e032c7" title="保存" type="button" class="scalable generate" onclick="save(this)"><span><span><span class="save-continue">保存活动</span></span></span></button></span>
            </td>
        </tr>
    </tbody></table>

</div>
<div class="entry-edit">
    <div class="entry-edit-head">
    <h4 class="icon-head head-edit-form fieldset-legend">基本信息</h4>
    <div class="form-buttons"></div>
</div>
    <div class="fieldset  ignore-validate" id="coupons_information_fieldset">
    <div class="hor-scroll">
    <table cellspacing="0" class="form-list">
        <tbody>
			<tr>
			    <td class="label"><label for="name">活动名称<span class="required">*</span></label></td>
			    <td class="value">
                <?php if($exchange && $exchange->getId()): ?>
                    <input type="hidden" name="id" id="exchange" value="<?php echo $exchange->getId(); ?>">
			        <input id="name" name="name" value="<?php echo $exchange->getName(); ?>" title="活动名称" class="required-entry input-text"  type="text">
                <?php else: ?>
                     <input id="name" name="name"  title="活动名称" class="required-entry input-text"  type="text">
                <?php endif; ?>
			    </td>
    		</tr>
    		<tr>
        		<td class="label"><label for="status">状态<span class="required">*</span></label></td>
    			<td class="value">
                    <?php if($exchange && $exchange->getId()): ?>
    	        		<select id="status" name="status" class="required-entry select">
                        <?php if($exchange->getStatus()): ?>
        					<option value="1"  selected="selected">启用</option>
        					<option value="0">禁用</option>
                        <?php else: ?>
                            <option value="1">启用</option>
                            <option value="0"  selected="selected">禁用</option>
    					</select>
                        <?php endif;?>
                    <?php else: ?>
                        <select id="status" name="status" class="required-entry select">
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                        </select>
                    <?php endif; ?>
				</td>
    		</tr>
            <?php 
                $websites = Mage::getModel('core/website')->getCollection()->toOptionHash();
                $websiteId =Mage::getSingleton('admin/session')->getUser()->getWebsiteId();
             ?>
            <tr>
                <td class="label"><label for="status">站点<span class="required">*</span></label></td>
                <td class="value">
                    <select id="website" name="website" class="required-entry select">
                    <?php if($exchange && $exchange->getId()): ?>
                    <option value="<?php echo $exchange->getWebsiteId(); ?>"><?php echo $websites[$exchange->getWebsiteId()]; ?></option>
                    <?php elseif($websiteId): ?>
                    <option value="<?php echo $websiteId; ?>"><?php echo $websites[$websiteId]; ?></option>  
                    <?php else: ?>
                    <option value="0"></option>
                    <?php foreach ($websites as $key => $website):?>
                    <option value="<?php echo $key ?>"><?php echo $website; ?></option>
                    <?php endforeach; ?>
                    </select>
                    <?php endif; ?>
                </td>
            </tr>
<!--			<tr>-->
<!--			    <td class="label"><label for="start_at">开始时间<span class="required">*</span></label></td>-->
<!--			    <td class="value">-->
<!--                    --><?php //if($exchange && $exchange->getId()): ?>
<!--			        <input id="start_at" name="start_at" value="--><?php //echo $exchange->getStartAt(); ?><!--" class="input-text required-entry" type="text">-->
<!--                    --><?php //else: ?>
<!--                    <input id="start_at" name="start_at" class="input-text required-entry" type="text">-->
<!--                    --><?php //endif; ?>
<!--			    </td>-->
<!--    		</tr>-->
            <tr>
                <td class="label"><label for="start_at">开始时间<span class="required">*</span></label></td>
                <td class="value">
                    <?php if($exchange && $exchange->getId()): ?>
                        <input id="start_at" class=" input-text" type="text" value="<?php echo $exchange->getStartAt(); ?>" name="start_at">
                        <img id="start_at_trig" class="v-middle" style="" title="Select Date" alt="" src="<?php echo $this->getSkinUrl('images/grid-cal.gif')?>">
                    <?php else: ?>
                        <input id="start_at" class=" input-text" type="text" value="" name="start_at">
                        <img id="start_at_trig" class="v-middle" style="" title="Select Date" alt="" src="<?php echo $this->getSkinUrl('images/grid-cal.gif')?>">
                    <?php endif; ?>
                </td>
            </tr>

			<tr>
			    <td class="label"><label for="end_at">结束时间<span class="required">*</span></label></td>
			    <td class="value">
                <?php if($exchange && $exchange->getId()): ?>
                    <input id="end_at" class=" input-text" type="text" value="<?php echo $exchange->getEndAt(); ?>" name="end_at">
                    <img id="end_at_trig" class="v-middle" style="" title="Select Date" alt="" src="<?php echo $this->getSkinUrl('images/grid-cal.gif')?>">
                <?php else: ?>
                    <input id="end_at" class=" input-text" type="text" name="end_at">
                    <img id="end_at_trig" class="v-middle" style="" title="Select Date" alt="" src="<?php echo $this->getSkinUrl('images/grid-cal.gif')?>">
                <?php endif; ?>
			    </td>
    		</tr>
    		<tr>
			    <td class="label"><label for="comment">活动详情</label><span class="required">*</span></td>
			    <td class="value">
                    <?php if($exchange && $exchange->getId()): ?>
			        <textarea name="description" id="description" class="required-entry" cols="25" rows="5" style="height:100px"><?php echo $exchange->getDescription(); ?></textarea>
                    <?php else: ?>
                        <textarea name="description" id="description" class="required-entry" cols="15" rows="2" style="height:100px"></textarea>
                    <?php endif; ?>        
			    </td>
    		</tr>
        </tbody>
    </table>
    </div>
    </div>
</div>
<div class="entry-edit">
    <div class="entry-edit-head">
    	<h4 class="icon-head head-edit-form fieldset-legend">用SKU拣商品</h4>
    	<div class="form-buttons"></div>
	</div>
    <div class="fieldset  ignore-validate" id="coupons_information_fieldset">
        <div class="hor-scroll">
            <table cellspacing="0" class="form-list">
                <tbody>
                    <tr>
                        <td class="label"><label for="sku">商品编号</label></td>
                        <td class="value">
                            <input id="searchproductid" title="Dash Every X Characters" class="input-text" type="text"><p class="note"><span>请输入完整商品编号</span></p>
                        </td>
                    </tr>
        			<tr>
        			    <td class="label"><label for="sku">SKU</label></td>
        			    <td class="value">
        			        <input id="sku" title="Dash Every X Characters" class="input-text" type="text"><p class="note"><span>请输入完整sku</span></p>
        			    </td>
            		</tr>
                    <tr>
                        <td class="label"><label for="sku">商品名称</label></td>
                        <td class="value">
                            <input id="searchproductname" title="Dash Every X Characters" class="input-text" type="text"><p class="note"><span>请输入完整商品名称</span></p>
                        </td>
                    </tr>
        			<tr>
                		<td class="label"></td>
        			    <td class="value">
        			        <span id="coupons_generate_button"><button id="id_3cf81872242ced1ce5317b5704e032c7" title="保存" type="button" class="scalable generate" onclick="check(this)"><span><span><span>拣商品</span></span></span></button></span></td>
            		</tr>
                </tbody>
            </table>
        </div>
    </div>
    <div class="entry-edit-head">
        <h4 class="icon-head head-edit-form fieldset-legend">可兑换商品列表</h4>
        <div class="form-buttons"></div>
    </div>
    <div class="fieldset  ignore-validate" id="coupons_information_fieldset">
        <div class="grid np">
            <div class="hor-scroll">
            <table cellspacing="0" class="data order-tables">
            <colgroup>
            <col width="1">
            <col width="1">
            <col width="1">
            <col width="1">
            <col width="1">
            <col width="1">
            <col width="1">
            <col width="1">
            <col>
            </colgroup>
            <thead>
            <tr class="headings">
            <th>商品id</th>
            <th><span class="nobr">商品名称</span></th>
            <th><span class="nobr">SKU</span></th>
            <th><span class="nobr">可兑换库存</span></th>
           <!-- <th><span class="nobr">兑换积分</span></th>-->
            <th><span class="nobr">排序</span></th>
            <th><span class="nobr">已兑换库存</span></th>
            <th><span class="nobr">操作</span></th>
            </tr>
            </thead>
            <?php 
                if($exchange && $exchange->getId()){
                    $websiteId = $exchange->getWebsiteId();
                    $activeId = $exchange->getId();
                    if($activeId){
                        $exchangeproducts = Mage::getModel("pms/exchangeproduct")
                                            ->getCollection()
                                            ->addFieldToFilter("activity_id",$activeId);
                    }
                }   
            ?>
            <tbody class="even" id="appendproduct">
            <?php if(isset($exchangeproducts)):?>
                <?php foreach($exchangeproducts as $data): ?>
                 <?php  $websiteqty = $this->getWebsiteqty($data['product_id'],$websiteId); ?> 
                    <tr class="parent">
                        <td class="productid"><?php echo  $data['product_id'] ?></td>
                        <td class="productname"><?php echo $data['name'] ?></td>
                        <td class="productsku"><?php echo  $data['sku'] ?></td>
                        <td><input onblur="checkInt(this)" class="qtys" type="text" exproId = "<?php echo $data["id"]; ?>" product="<?php echo $data['product_id'] ?>" pname="<?php echo $data['name'] ?>" sku="<?php echo $data['sku'] ?>" name="qty" value="<?php echo $data['qty']  ?>" websiteqty = "<?php echo $websiteqty ?>" /></td>
                       <!-- <td><input class ="points" type="text" onblur="checkInt(this)" name = "points" value="<?php echo $data["points"]; ?>" /></td>
                       -->
                        <td><input class ="position" onblur="checkInt(this)" type="text" name = "position" value="<?php echo $data["position"]; ?>" /></td>
                        <td><?php echo $data["exchanged_qty"] ?></td>
                        <td><p class="remove" exchangeproductId = "<?php echo $data["id"] ?>" activity="<?php echo $data["activity_id"] ?>">删除</p></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
            </table>
            </div>
        </div>
</div>



<script type="text/javascript">
    //<![CDATA[
    Calendar.setup({
        inputField: "start_at",
        ifFormat: "%Y-%m-%e %H:%M:%S",
        showsTime: true,
        button: "start_at_trig",
        align: "Bl",
        singleClick : true
    });
    //]]>
</script>
<script type="text/javascript">
    //<![CDATA[
    Calendar.setup({
        inputField: "end_at",
        ifFormat: "%Y-%m-%e %H:%M:%S",
        showsTime: true,
        button: "end_at_trig",
        align: "Bl",
        singleClick : true
    });
    //]]>
</script>
<script type="text/javascript">
    var  $j = jQuery.noConflict();  
    $j(document).ready(function(){ 
        //时间控件
      /*  $j('#start_at').datetimepicker({
              lang:"ch", 
              timepicker:false,
        });
        $j('#end_at').datetimepicker({
              lang:"ch",
              timepicker:false,
        });*/
/*
        laydate({
            elem: '#start_at',
            event: 'focus'
        });
        laydate({
            elem: '#end_at',
            event: 'focus'
        });
*/

    });

    //检查是否为数字
    function checkInt(k){
        if(isNaN(k.value)){
            layer.alert("请填写数字信息");
            k.value=null;
        }
    }

    //删除活动商品
    $j(".remove").bind("click",function(){
        var remove = $j(this);
        layer.confirm("确定要删除？",function(index){
            remove.parent().parent('.parent').remove();
            var exchangeproductId = remove.attr("exchangeproductId");
            var activity_id = remove.attr("activity");
            if(exchangeproductId){
                var url ="<?php echo $this->getUrl('admin_promotion/adminhtml_exchange/removeproduct'); ?>";
                var url = url + "exchangeproductId/"+exchangeproductId+"/activity_id/"+activity_id;
                $j.get(url,function(result){
                    if(result.error){
                        layer.alert(result.message);
                    }
                 },"json");
            }
            layer.close(index);
         });
       
    });

    //by sku find product
	function check(k){

        var website=$j("#website").children('option:selected').val();
        if(website==0){
            layer.alert("请先选择站点");
            return false;
        }
		var sku = $j("#sku").val();
        var productId = $j("#searchproductid").val();
        var productname = $j("#searchproductname").val();

        if(!sku && !productId && !productname){
            layer.alert("请输入搜索内容");
            return false;
        }

        var productsku = new Array(1);
        $j("td.productsku").each(function(){
            productsku.push($j(this).html());
          });

        if($j.inArray(sku, productsku)>0){
            layer.alert("该商品已在该列表中!");
            return false;
        }
        var productids =new Array(1);
         $j("td.productid").each(function(){
            productids.push($j(this).html());
          });
        if($j.inArray(productId, productids)>0){
            layer.alert("该商品已在该列表中!");
            return false;
        }
        var productnames =new Array(1);
         $j("td.productname").each(function(){
            productnames.push($j(this).html());
          });
        if($j.inArray(productname, productnames)>0){
            $j("#centerimage").hide();
            layer.alert("该商品已在该列表中!");
            return false;
        }

        var url ="<?php echo $this->getUrl('admin_promotion/adminhtml_exchange/productlist'); ?>";
        if(sku){
            var url = url + "sku/"+sku+"/websiteId/"+website;
        }else if(productId){
            var url = url + "product_id/"+productId+"/websiteId/"+website;
        }else if(productname){
            productname = productname.replace("/","replace");
            console.log(productname);
            var url = url +"websiteId/"+website+ "/name/"+productname;
        }
        $j("#centerimage").show();
        k.disabled="disabled";
        $j.get(url,function(result){
            if(result.error){
                k.disabled="";
                $j("#centerimage").hide();
                layer.alert(result.message);
            }else{
                k.disabled="";
                $j("#centerimage").hide();
                layer.msg('该商品已加入可兑换商品列表');
                var html = result.message;
                $j("#appendproduct").append(html); 
               //删除活动商品
               $j(".remove").bind("click",function(){
                    var remove = $j(this);
                    layer.confirm("确定要删除？",function(index){
                        remove.parent().parent('.parent').remove(); 
                        layer.close(index);
                    });
               });
            }

         },"json");
	}

    //save exchange activity
    function save(k){
        var name= $j("#name").val(); 
        var status= $j("#status").val();
        var website= $j("#website").val();
        var startat= $j("#start_at").val();
        var endat = $j("#end_at").val();
        var description = $j("#description").val();
        if(name =="" || status =="" || startat == "" || endat == "" || description =="" || website == "0"){
            layer.alert("带*号的都是必填项，请完善活动信息！");
            return false;
        }
        var id =$j("#exchange").val();
        var product =new Array();
        var i=0;
        var errors = new Array();
        var websiteqtys = new Array();
        $j("tr.parent").each(function(index,value){
           var pro = $j(this).find(".qtys");
           var productId = pro.attr("product");
           var qty  = pro.val();
           var name = pro.attr("pname");
           var sku = pro.attr("sku");
           var websiteqty = pro.attr("websiteqty");
           var exproId = pro.attr("exproId")?pro.attr("exproId"):null;
           var position =$j(this).find(".position").val();
           var points =$j(this).find(".points").val();
           if(qty=="" || points==""){
                errors[i] = name;
           }
           if((qty-websiteqty)>0){
                websiteqtys[i] = name;
           }
           product[i] = new Array(productId,qty,name,sku,position,exproId,points);
           i++;
          });
        if(errors.length>0){
            layer.alert("可兑换库存、排序都是必填！");
            return false;
        }
        if(websiteqtys.length>0){
            var names = websiteqtys.join(" ; ");
            var names = names + " ; "
            layer.alert(names+"的可兑换库存大于实际库存;请重新填写!");
            return false;
        }
        k.disabled="disabled";
        $j(".save-continue").html("保存中--");
        $j("#centerimage").show();

        var url = "<?php echo $this->getUrl('admin_promotion/adminhtml_exchange/save'); ?>";
        $j.get(url,{name:name,status:status,website:website,start_at:startat,end_at:endat,description:description,product:product,id:id},function(result){
                if(result.success){
                    $j("#centerimage").hide();
                    layer.msg(result.message);
                    var urls = "<?php echo $this->getUrl('admin_promotion/adminhtml_exchange/edit'); ?>";
                    var exchangeId = result.exchange_id;
                    var template_id = result.template_id?result.template_id:0;
                    var urls = urls + "exchange_id/"+exchangeId+"/template_id/"+template_id;
                    if(template_id==0){
                        window.location.href=urls; 
                    }else{
                        var urls = "<?php echo $this->getUrl('admin_promotion/adminhtml_exchange/index'); ?>";
                        window.location.href=urls; 
                    }
                    
                }
         },"json");
    }



</script>
